import pymysql
import sqlparse

from config.config import DB_HOST, DB_PORT, DB_NAME, DB_PASSWORD, DB_USER


def get_connection():
    connection = pymysql.Connection(
        host=DB_HOST,
        port=DB_PORT,
        database=DB_NAME,
        user=DB_USER,
        password=DB_PASSWORD,
        charset="utf8",
        autocommit=True
    )
    return connection

def execute_sql_file(file_path,procedure_name):
    connection=get_connection()
    cursor=connection.cursor()
    with open(file_path, "r",encoding="utf8") as f:
        sql = f.read()
        statements=sqlparse.split(sql)
        for statement in statements:
            cursor.execute(statement)

        cursor.callproc(procedure_name)

    cursor.close()
    connection.close()

#先删除数据，再初始化数据，然后供调试使用。与胶水文件中的夹具相反。
if __name__ == "__main__":
    execute_sql_file("../config/data_destroy.sql", "data_destroy")
    execute_sql_file("../config/warehouse_and_area_init.sql", "warehouse_and_area_init")
    execute_sql_file("../config/item_type_init.sql", "item_type_init")
